package com.zekdot.registerclient.service.impl;

import com.zekdot.registerclient.dao.EnrollTempletDao;
import com.zekdot.registerclient.dto.Envelope;
import com.zekdot.registerclient.entity.EnrollTempletEntity;
import com.zekdot.registerclient.service.EnrollTempletService;
import com.zekdot.registerclient.util.IdUtil;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Create by zekdot on 20-4-7.
 */
@Service
public class EnrollTempletServiceImpl implements EnrollTempletService {

    @Resource
    private EnrollTempletDao enrollTempletDao;
    @Override
    public Envelope save(String userId,EnrollTempletEntity enrollTempletEntity) {
        enrollTempletEntity.setId(IdUtil.getId(userId,enrollTempletEntity.getTitle(),enrollTempletEntity.getIntro()));
        enrollTempletEntity.setAuthor(userId);
        enrollTempletEntity.setSubTime(new Timestamp(new Date().getTime()));
        try {
            enrollTempletDao.save(enrollTempletEntity);
        }catch (DuplicateKeyException e){
            return new Envelope(1,"您可能已添加过相同名称和简介的模板，若确认没有添加过，请再次提交",null);
        }
        return Envelope.success;
    }

    @Override
    public Envelope get(String userId,String id) {
        EnrollTempletEntity enrollTempletEntity = enrollTempletDao.get(userId,id);
        return new Envelope(enrollTempletEntity);
    }

    @Override
    public Envelope delete(String userId, String id) {
        enrollTempletDao.delete(userId,id);
        return Envelope.success;
    }

    @Override
    public Envelope search(String userId,String title,String lastId,int length) {
        List<EnrollTempletEntity> list = enrollTempletDao.search(userId,title,lastId,length);
        return new Envelope(list);
    }

    @Override
    public Envelope self(String userId, String lastId, int length) {
        List<EnrollTempletEntity> list = enrollTempletDao.selfTemplet(userId,lastId,length);
        return new Envelope(list);
    }
}
